package bairui.international.console.web.timer;

import java.util.Date;
import java.util.List;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sh_lianjing.task.timer.ExpireTaskHandler;
import com.sh_lianjing.task.timer.ExpireTasker;
import com.sh_lianjing.task.timer.TaskData;

import bairui.international.model.domain.jpa.TB_Prize;
import bairui.international.model.status.State_Prize;
import bairui.international.service.Service_Prize;

@Component
public class TimerTasks_Prize {

//	private final static long expire = 1000 * 60 * 60 * 24;		//24小时
//	private final static long expire = 1000 * 60;				//1分钟
	
	@Autowired private Service_Prize service_Prize;
	final private ExpireTasker<TB_Prize> tasker = new ExpireTasker<>();
	
	@PostConstruct
	public void post() {
		//启动时先扫表
		List<MyTaskData> taskDatas = service_Prize
			.list(it->it.state.eq(State_Prize.Uped).or(it.state.eq(State_Prize.Downed)))
			.stream()
			.map(it->new MyTaskData(it))
			.collect(Collectors.toList());
		tasker.putAll(taskDatas);
		//执行
		tasker.start(1,new ExpireTaskHandler<TB_Prize>() {
			@Override
			public void run(TB_Prize order) {
				try {
					order = service_Prize.load(order);
					if(order.getState() == State_Prize.Uped || order.getState() == State_Prize.Downed){
						service_Prize.autoFinish(order.getId());
					}
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		});
	}
	
	public void put(TB_Prize order) {
		tasker.put(new MyTaskData(order));
	}
	
	public void remove(TB_Prize order) {
		tasker.remove(new MyTaskData(order));
	}
	
	public boolean contains(TB_Prize order) {
		return tasker.contains(new MyTaskData(order));
	}
	
	public void update(TB_Prize order) {
		tasker.update(new MyTaskData(order));
	}
	
	/*
	 * 数据
	 */
	public static class MyTaskData extends TaskData<TB_Prize>{

		public MyTaskData(TB_Prize data) {
			super(data);
		}

		@Override
		public int compareTo(Delayed o) {
			Date thisFinishDate = this.getData().getFinishTime();
			Date thatFinishDate = ((MyTaskData)o).getData().getFinishTime();
			if(thatFinishDate.before(thisFinishDate)){
				return 1;
			}else if(thatFinishDate.after(thisFinishDate)){
				return -1;
			}
			return 0;
		}

		@Override
		public long getDelay(TimeUnit unit) {
			return unit.convert(this.getData().getFinishTime().getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
		}

	}
	
}
